/**
 * @计算从某分某秒到某分某秒的时间差距
 *
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @subpackage	default
 */

#include <stdio.h>
#include <cs50.h>

struct time {
	int hours;
	int minutes;
	int seconds;
};

struct time elapsed_time(struct time before, struct time after);
struct time get_time(char* prompt);

int main(int argc, char *argv[]) {
	struct time time1, time2, elapsed;

	// 获取开始和结束时间
	time1 = get_time("请输入开始时间");
	time2 = get_time("请输入结束时间");

	// 计算时间差
	elapsed = elapsed_time(time1, time2);
	printf("时间相差是：%.2d:%.2d:%.2d\n", elapsed.hours, elapsed.minutes, elapsed.seconds);
}

//计算两个时间差距
struct time elapsed_time(struct time before, struct time after) {
	struct time elapsed;
	int seconds_before, seconds_after, seconds;
	bool is_next_day = false;

	// 处理过夜的情况
	if (after.hours < before.hours) {
		struct time elapsed1 = elapsed_time(before, (struct time) {23, 59, 59});
		struct time elapsed2 = elapsed_time((struct time) {0, 0, 0}, after);

		is_next_day = true;

		before = elapsed1;
		after = elapsed2;
	}

	// 将开始时间和结束时间转换成秒
	seconds_before = before.seconds + before.minutes * 60 + before.hours * 3600;	
	seconds_after = after.seconds + after.minutes * 60 + after.hours * 3600;

	// 计算两个秒数的差
	seconds = is_next_day ? (seconds_after + seconds_before) : (seconds_after - seconds_before);

	// 将秒数差转换为时间结构体
	elapsed.hours = seconds / 3600 ;
	elapsed.minutes = (seconds % 3600) / 60;
	elapsed.seconds = (seconds % 3600) % 60;

	return elapsed;
}

struct time get_time(char* prompt) {
	struct time t;

	do {
		// 获取合法的时间
		printf("%s(时:分:秒)：", prompt);
		scanf("%d:%d:%d", &t.hours, &t.minutes, &t.seconds);

		if (t.hours < 24 && t.hours >=0) {
			if (t.minutes < 60 && t.minutes >= 0) {
				if (t.seconds < 60 && t.seconds >= 0) {
					break;
				}
			}
		}  
	} while(true);

	return t;
}
